package com.siyu.rehearsal.grpc;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class RunShellScript {
    public static void runshell(String ctrlPath,String outputPath,String filePath) {
        xiugaidockershell(ctrlPath);  //修改docker内部的脚步
        xiugaimodelrunshell(filePath);
        try {
            ProcessBuilder pb = new ProcessBuilder("./shell/modelrun.sh");
            pb.redirectErrorStream(true);
            pb.redirectOutput(new File("/tmp/modelrun_output.log"));
            int exitCode = pb.start().waitFor();

            System.out.println("Script execution finished with exit code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void xiugaimodelrunshell(String filePath) {
        String itfPath = "./shell/modelrun.sh";
        String shell9 = "docker cp "+filePath+"*"+" \"$CONTAINER_ID\":/Inputs/";
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(itfPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 修改第三行和第六行
        if (lines.size() >= 9) {
            lines.set(8, shell9); // 第六行
        }

        // 写回文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(itfPath))) {
            for (String modifiedLine : lines) {
                writer.write(modifiedLine);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void xiugaidockershell(String ctrlPath) {
        String itfPath = "./shell/runmodel.sh";
        String shell16 = "./ITF_v204_GPU itf "+ctrlPath+" $ss -999.0 -999.0 2";
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(itfPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 修改第三行和第六行
        if (lines.size() >= 16) {
            lines.set(15, shell16); // 第六行
        }

        // 写回文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(itfPath))) {
            for (String modifiedLine : lines) {
                writer.write(modifiedLine);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //xiugaidockershell("ssss");
        xiugaimodelrunshell("45555/");
    }

}